package com.taiji.dicom4cloud.admin.service.impl;

import cn.hutool.core.util.ArrayUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.taiji.dicom4cloud.admin.dao.UserMapper;
import com.taiji.dicom4cloud.admin.service.SysUserService;
import com.taiji.dicom4cloud.common.core.constrant.constant.SecurityConstants;
import com.taiji.dicom4cloud.common.model.dto.UserInfo;
import com.taiji.dicom4cloud.common.model.entity.SysUser;
import com.taiji.dicom4cloud.common.security.service.IUserDetailService;
import lombok.AllArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * @Description
 * @Author fanxl
 * @Date 2021/5/20
 **/
@Service
@AllArgsConstructor
public class UserDetailServiceImpl extends ServiceImpl<UserMapper, SysUser> implements IUserDetailService {


    private final SysUserService sysUserService;

    @Override
    public SysUser getByUsername(String username) {
        return this.getOne(Wrappers.<SysUser>lambdaQuery().eq(SysUser::getUsername,username));
    }

    @Override
    public Collection<? extends GrantedAuthority>  getUserInfo(SysUser sysUser) {
        return loadUserInfo(sysUserService.getUserInfo(sysUser));
    }

    public Collection<? extends GrantedAuthority> loadUserInfo(UserInfo info){
        Set<String> dbAuthsSet = new HashSet<>();
        if (ArrayUtil.isNotEmpty(info.getRoles())) {
            // 获取角色
            Arrays.stream(info.getRoles()).forEach(role -> dbAuthsSet.add(SecurityConstants.ROLE + role));
            // 获取资源
            dbAuthsSet.addAll(Arrays.asList(info.getPermissions()));
        }

        Collection<? extends GrantedAuthority> authorities = AuthorityUtils
                .createAuthorityList(dbAuthsSet.toArray(new String[0]));
        return authorities;
    }
}
